<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {deleteFixtureLedger, findFixtureLedgers} from "@/apis/zyj/FixtureLedger.js";
import addFixture from "@/components/FixtureLedger/AddDialog.vue"
import updateFixture from "@/components/FixtureLedger/UpdataDialog.vue"
import {findTypeSets} from "@/apis/zyj/typeSetting.js";

function initData() {
  findFixtureLedgers(formInline, currentPage.value, pageSize.value).then(res => {
    tableData.length = 0
    tableData.push(...res.records);
    total.value = res.total;
    currentPage.value = res.current;
  })
}

function initTypeDate() {
  findTypeSets('', '', '', -1, -1).then(res => {
    typeData.length = 0;
    Object.assign(typeData, res)
  })
}

onMounted(() => {
  initData()
  initTypeDate()
})


const formInline = reactive({
  fixtureCode: '',
  fixtureName: '',
  typeCode: '',
  brand: '',
  model: '',
  status: ''
})

const typeData = reactive([])
const tableData = reactive([])
const addDialog = ref(false)
const updateDialog = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理

const onSearch = () => {
  initData()
}

const onReset = () => {
  Object.keys(formInline).forEach(key => formInline[key] = '')
}
//新增按钮
const onAdd = () => {
  addDialog.value = true
}


//导出按钮
const onExport = () => {
  ElMessage.success('导出 clicked')
}
//修改按钮
const handleEdit = (row) => {
  if (row.fixtureCode != null) {
    multipleSelection.value = {...row}
  } else {
    multipleSelection.value = {...multipleSelection.value[0]}
  }
  updateDialog.value = true
}
// 删除事件
const handleDelete = (row) => {
  if (row.fixtureCode != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.fixtureCode != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.fixtureCode)
        }
        deleteFixtureLedger(select_orderId.value).then((res) => {
          if (res == '成功') {
            initData()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = 0;
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

//分页
const handleSizeChange = (val) => {
  initData()
}
const handleCurrentChange = (val) => {
  initData()
}
//关闭弹窗
const closeDialog = () => {
  addDialog.value = false
  updateDialog.value = false
  initData()
  multipleTable.value.clearSelection();
}

//选中事件
const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.fixtureCode);
      }
    });
  }
}
//获取表格行的key值
const getRowKeys = (row) => {
  //记录每行的key值
  return row.id;
}
</script>


<template>
  <div class="equipment-management">
    <el-card>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="工装夹具编码">
        <el-input v-model="formInline.fixtureCode" placeholder="请输入工装夹具编码"/>
      </el-form-item>
      <el-form-item label="工装夹具名称">
        <el-input v-model="formInline.fixtureName" placeholder="请输入工装夹具名称"/>
      </el-form-item>
      <el-form-item label="工装夹具类型">
        <el-select v-model="formInline.typeCode" placeholder="请选择类型" style="width: 140px;">
          <el-option v-for="s in typeData" :label="s.typeName" :value="s.typeCode"/>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌">
        <el-input v-model="formInline.brand" placeholder="请输入品牌"/>
      </el-form-item>
      <el-form-item label="型号">
        <el-input v-model="formInline.model" placeholder="请输入型号"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="请选择状态" style="width: 120px;">
          <el-option label="在库" value="1"/>
          <el-option label="被领用" value="2"/>
          <el-option label="报废" value="3"/>
          <el-option label="维修中" value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
    <div class="table-operations">
      <el-button type="primary" @click="onAdd" plain>新增</el-button>
      <el-button type="success" @click="handleEdit" :disabled="select_order_number!=1" plain>修改</el-button>
      <el-button type="danger" @click="handleDelete" :disabled="select_order_number==0" plain>删除</el-button>
    </div>

    <el-table :data="tableData" ref="multipleTable" :row-key="getRowKeys" @selection-change="handleSelectionChange"
              style="width: 100%" :header-cell-style="{'text-align':'center','font-size':'13px'}"
              :cell-style="{'text-align':'center','font-size':'13px'}" max-height="330px">
      <el-table-column type="selection" width="50"/>
      <el-table-column prop="fixtureCode" label="编号" width="105"/>
      <el-table-column prop="fixtureName" label="名称" width="100"/>
      <el-table-column prop="brand" label="品牌" width="100"/>
      <el-table-column prop="model" label="型号" width="100"/>
      <el-table-column prop="fixtureTypes.typeName" label="类型" width="100"/>
      <el-table-column prop="quantity" label="库存数量" width="100"/>
      <el-table-column prop="availableQuantity" label="可用数量" width="100"/>
      <el-table-column prop="maintenanceType" label="保养维护类型" width="100"/>
      <el-table-column prop="nextMaintenancePeriod" label="下次保养周期" width="100"/>
      <el-table-column prop="nextMaintenanceDate" label="下次保养日期" width="120"/>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          {{
            scope.row.status == 1 ? '在库' : scope.row.status == 2 ? '被领用' : scope.row.status == 3 ? '报废' : '维修中'
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    </el-card>
    <add-fixture :addDialog="addDialog" :typeDate="typeData" @close-dialog="closeDialog"/>
    <update-fixture :updateDialog="updateDialog" :form="multipleSelection" :typeDate="typeData"
                    @close-dialog="closeDialog"/>
  </div>
</template>

<style scoped>
.equipment-management {
  padding: 20px;
}

.table-operations {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

</style>